package org.franca.importer.ea;

import java.io.File;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.franca.core.dsl.FrancaIDLHelpers;
import org.franca.importer.ea.processor.AppearanceCustomizer;
import org.franca.importer.ea.processor.AutoResolver;
import org.franca.importer.ea.processor.DependencyResolver;
import org.franca.importer.ea.processor.DummyProcessor;
import org.franca.importer.ea.processor.ElementCreator;
import org.franca.importer.ea.processor.FindByName;
import org.franca.importer.ea.processor.ImportProcessor;
import org.franca.importer.ea.processor.NotesUpdater;
import org.franca.importer.ea.utils.CommandLineHelper;
import org.franca.importer.ea.utils.FileScanner;

public class ImporterMain {


	private static Logger jlog = Logger.getLogger(ImporterMain.class
			.getName());

	
	public int doImport(String[] args) {
		
		ImporterFacade facade = new ImporterFacade();
				
		CommandLineHelper cliOptions = new CommandLineHelper();
		cliOptions.createOptions();
		cliOptions.parseOptions(args);
				
		if (cliOptions.getEaProject() != null
				&& cliOptions.getRootPackage() != null
				&& cliOptions.getFrancaPath() != null) {

			FileScanner fScanner = new FileScanner();
			List<String> francaModels = fScanner.getFiles(cliOptions.getFrancaPath());

			// try to open project and find the root Package
			if(!facade.setup(cliOptions.getEaProject(), true, cliOptions.getRootPackage(), true)) {
				facade.tearDown();
				return -1;
			}
			
			// configure the feature set of the importer
			ImportProcessor preProcessor = new AppearanceCustomizer( 
				new NotesUpdater(
					new DependencyResolver(
						new ElementCreator(
							new AutoResolver(
								new FindByName(new DummyProcessor()))))));

			Franca2EA importer = new Franca2EA(preProcessor);			
			facade.setImporter(importer);
			
			// Load all Franca Models and sort them to solve the dependency chain
			for(int i=0; i<francaModels.size(); i++) {
				File francaFile = new File(francaModels.get(i));
				facade.addModel(FrancaIDLHelpers.instance().loadModel(
						francaFile.getAbsolutePath()), francaFile.getName().split("\\.")[0]);
			}
			
			// now start the importer
			facade.processImport();
			
			// tear everything down
			facade.tearDown();
			
			return 0;
		}
		
		else {
			return -2;
		}
		
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {

		ImporterMain importer = new ImporterMain();
		
		int result = importer.doImport(args);
		
		switch(result) {
			case 0:
				jlog.log(Level.INFO, "Import successfully finished"); 
				break;
			case -1:
				jlog.log(Level.SEVERE, "Failed to open or create project");
				break;
			case -2:
				jlog.log(Level.SEVERE, "Please specify import parameter");
				break;
			default:
				break;
		}
		
		System.exit(result);
		
	}

}
